from django.contrib.auth.backends import ModelBackend
import re
from .models import User


def get_user_by_account(account):
    '''
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    '''
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        # 不存在返回none
        return None

    else:
        # 返回用户
        return user


class UsernameMobileAuthBackend(ModelBackend):
    '''自定义用户登录检测类'''

    def authenticate(self, request, username=None, password=None, **kwargs):
        '''
        检测用户名和密码
        :param request: 请求
        :param username:用户名
        :param password: 密码
        :param kwargs: 其余
        :return: 是否登录成功
        '''


        # 同伙手机号或者用户名获得账户
        user = get_user_by_account(username)

        # 通过用户名检验密码
        if user and user.check_password(password):
            return user
